<!--权限管理-->
<template>
  <section class="app-container">
    <div class="content">
      <!--工具条-->
      <div class="body-top clearfix">
        <div class="body-top-left">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane v-for="item in systemList" :key="item.menuId" :label="item.name" :name="item.menuId">
              <!-- {{ item.content }} -->
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="body-top-right text-right">
          <el-button v-p="'menuManageAddSystem'" type="primary" size="small" style="margin-bottom:10px" @click="openPermissionDialogByBtn('增加系统')">增加系统</el-button>
          <el-button type="primary" size="small" style="margin-bottom:10px" @click="getTableList">刷新</el-button>
        </div>
      </div>
      <div class="content-tree">
        <!--列表 -->
        <el-table
          v-loading="tableListLoading"
          :data="subSystemList"
          row-key="menuId"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          highlight-current-row
          height="690"
          size="small"
          stripe
          border
        >
          <el-table-column type="index" label="序号" width="46" fixed />
          <el-table-column prop="name" label="权限名" min-width="120" sortable />
          <el-table-column prop="mark" label="权限标识" min-width="140" sortable />
          <el-table-column prop="menuType" label="权限类型" min-width="100" sortable>
            <template slot-scope="scope">
              <span v-if="scope.row.menuType===0"><i class="el-icon-document text-warning" />{{ scope.row.menuType | transformPermissionType }}</span>
              <span v-if="scope.row.menuType===1"><i class="el-icon-reading text-success" />{{ scope.row.menuType | transformPermissionType }}</span>
              <span v-if="scope.row.menuType===2"><i class="el-icon-mouse text-blue" />{{ scope.row.menuType | transformPermissionType }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="页面路径" min-width="120" sortable show-overflow-tooltip />
          <el-table-column prop="sortNum" label="同级排序" min-width="60" />
          <el-table-column prop="status" label="状态" min-width="70" sortable>
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" disabled active-color="#13ce66" inactive-color="#ff4949" :active-value="1" :inactive-value="0" />
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="150" fixed="right">
            <template slot-scope="scope">
              <a v-p="'menuManageAddSubSystem'" href="javascript:;" class="text-blue inline-block" @click="append(scope.row)">增加子菜单</a>
              <a v-p="'menuManageUpdate'" href="javascript:;" class="text-blue inline-block" @click="edit(scope.row)"><i class="el-icon-edit" />编辑</a>
              <a v-p="'menuManageIsUse'" href="javascript:;" class="text-blue inline-block" @click="switchStaus(scope.row)"><i class="el-icon-remove" />{{ scope.row.status===1?'停用':'启用' }}</a>
              <a v-p="'menuManageDelete'" href="javascript:;" class="text-danger inline-block" @click="deleteItem(scope.row)"><i class="el-icon-delete" />删除</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div>
      <!--权限新增/修改  -->
      <el-dialog :title="dialogTitle" :visible.sync="permissionVisible" :close-on-click-modal="false" @open="listenOpenPermissionDialog" @close="listenClosePermissionDialog">
        <el-form ref="permissionFormData" :model="permissionFormData" label-width="160px" :rules="permissionFormDataRules">
          <el-form-item label="权限类型:" prop="menuType" placeholder="请选择权限类型">
            <el-select v-model="permissionFormData.menuType">
              <el-option :value="0" label="目录" />
              <el-option :value="1" label="菜单" />
              <el-option :value="2" label="按钮" />
            </el-select>
          </el-form-item>
          <el-form-item label="权限名:" prop="name">
            <el-input v-model.trim="permissionFormData.name" placeholder="请输入权限名" clearable maxlength="50" />
          </el-form-item>
          <el-form-item label="权限标识:" prop="mark">
            <el-input v-model.trim="permissionFormData.mark" :disabled="isUpdateItem" placeholder="请输入权限标识(英文,用于前端判断)" clearable maxlength="100" />
          </el-form-item>

          <el-form-item label="同级排序:" prop="sortNum">
            <el-input-number v-model="permissionFormData.sortNum" clearable :min="1" :max="1000" placeholder="请输入当前级的排序顺序" label="请输入当前级的排序顺序" />
          </el-form-item>
          <el-form-item label="页面路径:" prop="path">
            <el-input v-model.trim="permissionFormData.path" placeholder="路由或跳转路径" clearable />
          </el-form-item>
          <el-form-item label="页面资源文件路径:" prop="component">
            <el-input v-model.trim="permissionFormData.component" placeholder="组件对应的文件路径" clearable />
          </el-form-item>
          <el-form-item label="目录图标:" prop="icon">
            <el-input v-model.trim="permissionFormData.icon" placeholder="fa fa-credit-card" clearable />
          </el-form-item>
          <el-form-item label="是否显示菜单:" prop="showMenu">
            <el-select v-model="permissionFormData.showMenu">
              <el-option :value="1" label="是" />
              <el-option :value="0" label="否" />
            </el-select>
          </el-form-item>
          <el-form-item label="启用状态:" prop="status">
            <el-select v-model="permissionFormData.status">
              <el-option :value="1" label="启用" />
              <el-option :value="0" label="关闭" />
            </el-select>
          </el-form-item>
          <el-form-item label="描述:" prop="description">
            <el-input v-model.trim="permissionFormData.description" type="textarea" placeholder="在此输入描述" maxlength="300" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="permissionVisible = false">取消</el-button>
          <el-button type="primary" @click="permissionFormSubmit('permissionFormData')">立即提交</el-button>
        </div>
      </el-dialog>
    </div>
  </section>
</template>

<script>
import { validEnglish } from '@/utils/validate'
import { queryAllMenu, addMenu, updateMenu, isUseMenu, deleteMenu } from '@/api/api'

export default {
  filters: {
    transformPermissionType(value) {
      return value === 0 ? '目录' : value === 1 ? '菜单' : value === 2 ? '按钮' : '未知' + value
    }
  },
  data() {
    return {
      activeName: '1',
      tableListLoading: false,
      dialogTitle: '新增权限',
      // 列表信息
      permissionVisible: false,
      permissionFormData: {
        parentId: '',
        name: '',
        mark: '',
        sortNum: '',
        menuType: 2,
        path: '',
        component: '',
        icon: '',
        showMenu: 1,
        status: 1,
        description: ''
      },
      permissionFormDataRules: {
        menuType: [
          { required: true, message: '请选择权限类型', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入权限名', trigger: 'blur' }
        ],
        mark: [
          { required: true, validator: validEnglish, trigger: 'blur' }
        ],
        sortNum: [
          { required: true, message: '请输入当前级的排序顺序', trigger: 'change' }
        ]
      },
      isUpdateItem: false, // 控制表单不可修改的项
      permissionDataAll: null, // 所有系统权限
      systemList: [], // 所有系统
      subSystemList: [] // 系统对应的权限

    }
  },
  mounted() {
    this.getTableList()
  },
  methods: {
    // 查所有系统权限
    getTableList() {
      this.tableListLoading = true
      queryAllMenu({}).then(res => {
        this.tableListLoading = false
        if (res.code === '0000') {
          // 所有权限
          this.permissionDataAll = res.data
          // 所有系统
          this.systemList = []
          for (let i = 0; i < this.permissionDataAll.length; i++) {
            const tempObj = {
              menuId: this.permissionDataAll[i].menuId,
              name: this.permissionDataAll[i].name
            }
            this.systemList.push(tempObj)
          }
          // 系统下的权限
          this.subSystemList = this.getSubSystemList(this.activeName)
        }
      // eslint-disable-next-line handle-callback-err
      }).catch(error => {
        this.tableListLoading = false
      })
    },
    // 根据id查对应系统下的权限
    getSubSystemList(menuId) {
      for (let i = 0; i < this.permissionDataAll.length; i++) {
        if (this.permissionDataAll[i].menuId === menuId) {
          const tempList = []
          tempList.push(this.permissionDataAll[i])
          return tempList
        }
      }
    },

    // 新增一级菜单
    openPermissionDialogByBtn(dialogTitle) {
      this.dialogTitle = dialogTitle
      this.permissionVisible = true
      if (this.dialogTitle === '增加系统') {
        this.permissionFormData.parentId = 0
      }
    },
    // tab切换
    handleClick(tab, event) {
      // 把系统id绑定到tab里,每次切换根据id查系统下的权限
      this.subSystemList = this.getSubSystemList(this.activeName)
    },
    // 监听弹窗打开
    listenOpenPermissionDialog() {

    },
    // 监听弹窗关闭
    listenClosePermissionDialog() {
      // 初始化表单状态
      this.$refs['permissionFormData'].resetFields()

      this.Utils.emptyObject(this.permissionFormData)
      this.permissionFormData.menuType = 2
      this.permissionFormData.showMenu = 1
      this.permissionFormData.status = 1
      this.isUpdateItem = false
    },
    // 表单提交
    permissionFormSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogTitle === '修改权限') {
            updateMenu(this.permissionFormData).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.permissionVisible = false
                this.getTableList()
              }
            })
          } else {
            addMenu(this.permissionFormData).then(res => {
              if (res.code === '0000') {
                this.$message({
                  message: '操作成功',
                  type: 'success'
                })
                this.permissionVisible = false
                this.getTableList()
              }
            })
          }
        } else {
          return false
        }
      })
    },

    // 新增子菜单
    append(row) {
      // console.log(row)
      this.dialogTitle = '新增子菜单'
      this.permissionVisible = true
      this.permissionFormData.parentId = row.menuId
      this.permissionFormData.sortNum = this.Utils.getMaxSort(row.children, 'sortNum')
    },
    // 节点上修改权限
    edit(row) {
      // console.log(row)
      // 不能修改系统的权限标识mark
      if (row.parentId === '0') {
        this.isUpdateItem = true
      } else {
        this.isUpdateItem = false
      }
      this.dialogTitle = '修改权限'
      this.permissionVisible = true
      this.permissionFormData = this.Utils.deepCopy(row)
    },
    // 切换启用状态
    switchStaus(row) {
      const params = {
        menuId: row.menuId,
        status: Number(!row.status)
      }
      const operatType = row.status === 1 ? '停用' : '启用'
      this.$confirm(`您确定要${operatType}权限"${row.name}"吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        isUseMenu(params).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getTableList(false)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 删除
    deleteItem(row) {
      this.$confirm(`您确认删除[${row.name}]吗?`, '提示', {
        type: 'warning'
      }).then(() => {
        deleteMenu({ menuId: row.menuId }).then(res => {
          if (res.code === '0000') {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.permissionVisible = false
            this.getTableList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    }
  }
}

</script>

<style lang="scss" scoped>
.app-container{
  .content{
    .body-top{
      .body-top-left{
        float: left;
        width: 69%;
      }
      .body-top-right{
        float: right;
        width: 30%;
      }
    }
  }
}

</style>

